package cn.com.cetccst.activation.ui.viewmodel;


import static cn.com.cetccst.tools.kv.CommonKV.kvStore;

import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.google.gson.annotations.SerializedName;

import cn.com.cetccst.activation.kv.KVKeys;
import cn.com.cetccst.activation.ui.dialog.viewmodel.ProcessViewModel;

public class ActivationViewModel extends ViewModel {

    public MutableLiveData<AuthData> authData = new MutableLiveData<>();

    private ProcessViewModel processViewModel;

    public void registerObserver(FragmentActivity activity, ProcessViewModel.Callback callback) {
        authData.observe(activity, authData -> {
            kvStore.encode(KVKeys.KEY_USER_ID, authData.getUserId());
            processViewModel.requestAuth(activity, authData, callback);
        });
    }

    public void setProcessViewModel(ProcessViewModel processViewModel) {
        this.processViewModel = processViewModel;
    }

    public static class AuthData {
        public static final String SEPARATOR = "-";
        @SerializedName("email")
        private String email;
        @SerializedName("pin")
        private String pin;
        @SerializedName("server")
        private String server;
        private AuthType authType = AuthType.PIN;

        private String accessToken;

        public AuthType getAuthType() {
            return authType;
        }

        public String getUserId() {
            return email;
        }

        public String getAccessKey() {
            String[] pinArray = pin.split(SEPARATOR);
            if (pinArray.length >= 3) {
                return pinArray[0] + pinArray[1] + pinArray[2];
            } else {
                return pin;
            }
        }

        public String getOtaServer() {
            return server;
        }

        public String getAccessToken() {
            return accessToken;
        }

        public void setAccessToken(String accessToken) {
            this.accessToken = accessToken;
        }

        public enum AuthType {

            PIN, SMS, PHONE, PRE;

            public static AuthType fromOrdinal(int ordinal) {
                if (ordinal >= 0) {
                    for (AuthType authType : AuthType.values()) {
                        if (authType.ordinal() == ordinal) {
                            return authType;
                        }
                    }
                }
                return null;
            }
        }
    }
}
